package com.hoow.shakoow.shake.msgNotify

import android.os.Handler
import android.os.Looper
import com.google.gson.Gson
import com.hoow.shakoow.ai.data.*
import com.hoow.shakoow.ai.network.ApiAiPathUrl
import com.hoow.shakoow.ai.network.ApiAiServiceCreator
import com.hoow.shakoow.extend.toFullUrlPath
import com.hoow.shakoow.utils.UserStateUtil
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONException
import java.io.IOException
import java.util.*

class GreetMsgNotify(val retrySec: Int = 20) {

    // 消息监听
    private var mGreetMsgListener: GreetMsgListener? = null

    // 调用句柄
    private var mHttpClient: OkHttpClient? = null

    // 调用句柄
    private var mNotifyHandler = Handler(Looper.getMainLooper())

    /**
     * 退出
     */
    fun releaseResrouce() {
        mNotifyHandler.removeCallbacksAndMessages(null)
    }

    /**
     * 打招呼监控
     * 1分钟轮询1次
     */
    fun setGreetMsgListener(listener: GreetMsgListener) {
        mGreetMsgListener = listener
    }

    /**
     * 获取调用句柄
     */
    fun getHttpClient(): OkHttpClient? {
        if (mHttpClient == null) {
            mHttpClient = ApiAiServiceCreator.getGreetMsgClient()
        }
        return mHttpClient
    }

    /**
     * 打招呼监控
     * 1分钟轮询1次
     */
    fun startGreetMsgListener() {
        getHttpClient()?.let { client ->
            val info = Gson().toJson(ReqAiBase()).trim()
            val body: RequestBody = info
                .toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())

            val request: Request = Request.Builder()
                .url(ApiAiPathUrl.PATH_GET_GREET_MSG.toFullUrlPath())
                .addHeader("Authorization", UserStateUtil.mToken)
                .post(body)
                .build()

            val call = client.newCall(request)

            call.enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    println("getSessionId failure：${e.localizedMessage}")
                    // 1分钟后重新拉取消息
                    retryGreetMsgFetching()
                }

                override fun onResponse(call: Call, response: Response) {
                    response.body?.let {
                        val result = Objects.requireNonNull(it).string()
                        onHandlerHttpResponse(result)
                    }
                    // 1分钟后重新拉取消息
                    retryGreetMsgFetching()
                }
            })
        }
    }

    /**
     * 直接查询消息列表
     */
    fun reloadGreetMsgNow() {
        getHttpClient()?.let { client ->
            val info = Gson().toJson(ReqAiBase()).trim()
            val body: RequestBody = info
                .toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())

            val request: Request = Request.Builder()
                .url(ApiAiPathUrl.PATH_GET_GREET_MSG.toFullUrlPath())
                .addHeader("Authorization", UserStateUtil.mToken)
                .post(body)
                .build()

            val call = client.newCall(request)

            call.enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    println("getSessionId failure：${e.localizedMessage}")
                }

                override fun onResponse(call: Call, response: Response) {
                    response.body?.let {
                        val result = Objects.requireNonNull(it).string()
                        onHandlerHttpResponse(result)
                    }
                }
            })
        }
    }

    /**
     * 1分钟后重新拉取消息
     */
    private fun retryGreetMsgFetching() {
        // 移除 call back
        mNotifyHandler.removeCallbacksAndMessages(null)
        mNotifyHandler.postDelayed({
            startGreetMsgListener()
        }, retrySec * 1000L)
    }

    /**
     * 处理请求返回消息
     */
    private fun onHandlerHttpResponse(resData: String) {
        try {
            val revLastGreetMsg =
                Gson().fromJson(resData, RevLastGreetMsg::class.java)

            revLastGreetMsg?.let { result ->
                if (result.code.toInt() == 0) {
                    println("PATH_SHAKE_HISTORY success")
                } else {
                    println("PATH_SHAKE_HISTORY error：${result.msg}")
                }
                // 处理消息
                onHandlerMsgList(result.data)
            }
        } catch (e: JSONException) {
            throw RuntimeException(e)
        }
    }

    /**
     * 处理消息回调
     */
    private fun onHandlerMsgList(revObjLastGreetMsg: RevObjLastGreetMsg?) {
        Handler(Looper.getMainLooper()).post {
            if (revObjLastGreetMsg == null) {
                mGreetMsgListener?.onNotMatchNewMsg()
            }

            revObjLastGreetMsg?.let { result ->
                result.newMsg?.let { unReadCount ->
                    if (unReadCount.isNotBlank()) {
                        val unReadCountInt = unReadCount.toInt()
                        if (unReadCountInt > 0) {
                            mGreetMsgListener?.onMsgDetected(unReadCountInt)
                        } else {
                            mGreetMsgListener?.onNotMatchNewMsg()
                        }
                    } else {
                        mGreetMsgListener?.onNotMatchNewMsg()
                    }
                }

                if (result.newMsg == null) {
                    mGreetMsgListener?.onNotMatchNewMsg()
                }
            }
        }
    }
}